<?php # DBObject.php

require_once '../mysqlConnect.php';

class DBObject {
	
	public function find ($tableName) {
		
		$DBH = GetPDOConnection();
		$variables = $this->get();
		
		$parameters = array();
		foreach($variables as $key => $value) {
			if ($key != "id" && $key != "ID")
				$parameters[] = "$key = '$value'";
		}
		
		$parameterString = join(' AND ', array_values($parameters));
		$query = sprintf("SELECT * FROM %s WHERE %s", $this->tablename, $parameterString);
		$STH = $DBH->prepare($query);
		$STH->setFetchMode(PDO::FETCH_CLASS, $tableName);
		$STH->execute();
		$result = $STH->fetchAll();
		$DBH = null;

		return $result;
	}
	
	public function save() {
		
		$validate = $this->validate();
		if ($validate === NULL) {
			$DBH = GetPDOConnection();
			$variables = $this->get();
			$query= sprintf("INSERT INTO %s (%s) VALUES ('%s')", $this->tablename, join(', ', array_keys($variables)), join("', '", array_values($variables)));
			$STH = $DBH->prepare($query);
	
			if ($STH->execute() === true) {
				$DBH = null;
				return true;
			}
			else {
				$DBH = null;
				return "Error when attempting to save to database";
			}
		}
		else
			return $validate;#"Confliction or missing medication data in object construction";
	}
	
	public function validateObject($tableName) {
	
		$result = $this->get();
		foreach ($result as $key => $value) {
			if ($key != "id" && $key != "ID") {
				if (!isset($value))
					return "Missing parameter: $key";
				if (trim($value) === "")
					return "Entry is blank: $key";
			}
		}
		
		$existingEntry = $this->find($tableName);
		if (count($existingEntry) > 0)
			return "Conflicting Database Entry";
		else
			return null;
	}
	
	public function set ($vars) {
		foreach ($vars as $key => $value)
		$this->$key = $value;
	}
}